package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"os/exec"
	"path"
	"path/filepath"
	"studygo/other/picutils"
	"sync"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
	log.SetPrefix("TRACE: ")
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

var (
	wg sync.WaitGroup
)

func main() {
	pathCMD := flag.String("path", "D:\\AAA", "文件地址")
	flag.Parse()
	filePath := *pathCMD
	files, _ := picutils.GetAllFilesOnly(filePath)
	picutils.MkdirFileAll(filePath, "trans")
	for _, file := range files {
		if picutils.GetFileSize(file) > 1024*1024*1025*1.5 {

			wg.Add(1)
			go func(fileName string) {
				defer wg.Done()
				//fmt.Println(fileName)
				slash := filepath.ToSlash(fileName)
				//fmt.Println(path.Base(slash))
				RunCommand("ffmpeg", "-i", fileName,
					"-vcodec", "libx264", "-crf", "22", "-preset", "veryfast", "-c:a", "copy",
					"-y", filePath+"/trans/"+path.Base(slash))

			}(file)
		}
	}

	wg.Wait()
	//压缩视频
	//RunCommand("ffmpeg", "-i", filePath+"/02-第二课—知行合一.mp4",
	//	"-vcodec", "libx264", "-crf", "22", "-preset", "veryfast", "-c:a", "copy", "-y", filePath+"/trans/02-第二课—知行合一.mp4")

}
func RunCommand(name string, arg ...string) error {
	cmd := exec.Command(name, arg...)
	// 命令的错误输出和标准输出都连接到同一个管道
	stdout, err := cmd.StdoutPipe()
	cmd.Stderr = cmd.Stdout
	if err != nil {
		return err
	}
	if err = cmd.Start(); err != nil {
		return err
	}
	// 从管道中实时获取输出并打印到终端
	for {
		tmp := make([]byte, 1024)
		_, err := stdout.Read(tmp)
		logs := string(tmp)
		if "" != logs {
			fmt.Println(logs)
		}

		if err != nil {
			break
		}
	}
	if err = cmd.Wait(); err != nil {
		return err
	}
	return nil
}
